let _map;
let _editLayer = null;
let DRAWING = false; //是否正在绘制
let DRAWLAYERS = [];
let BarDRAWLAYERS = [];
let ISMEASURE = false;  //是否是量距
let MEASURETOOLTIP;  //量距提示
let MEASUREAREATOOLTIP;  //量面提示
let MEASURERESULT = 0;
let DRAWPOLYLINE; //绘制的折线
let DRAWMOVEPOLYLINE; //绘制过程中的折线
let DRAWPOLYLINEPOINTS = []; //绘制的折线的节点集
let DRAWPOLYGON; //绘制的面
let DRAWMOVEPOLYGON; //绘制过程中的面
let DRAWPOLYGONPOINTS = []; //绘制的面的节点集
const LineMeasure = function(){
	this.lineMeasure = function(map,editLayer){
		_map= map;
		_editLayer = editLayer;
		//清除底图上原有的图层
		_editLayer.clearLayers();
		ISMEASURE = true;
		this.startDrawLine();
	}
	this.areaMeasure = (map,editLayer) => {
		_map= map;
		_editLayer = editLayer;
		//清除底图上原有的图层
		_editLayer.clearLayers();
		ISMEASURE = true;
		this.startDrawPolygon();
	}
	/**
	 * 测距
	 */
	this.startDrawLine = function(func){
		const that = this;
		MEASURERESULT = 0;
		_map.getContainer().style.cursor = 'pointer';
		_map.on('mousedown', function (e) {
		    DRAWING = true;
		    DRAWPOLYLINEPOINTS.push(e.latlng);
		    if (DRAWPOLYLINEPOINTS.length > 1 && ISMEASURE) {
		        MEASURERESULT += e.latlng.distanceTo(DRAWPOLYLINEPOINTS[DRAWPOLYLINEPOINTS.length - 2]);
		    }
		    DRAWPOLYLINE.addLatLng(e.latlng);
		});
		_map.on('mousemove', function (e) {
		    if (DRAWING) {
		        if (DRAWMOVEPOLYLINE != undefined && DRAWMOVEPOLYLINE != null) {
		            _editLayer.removeLayer(DRAWMOVEPOLYLINE);
		        }
		        let prevPoint = DRAWPOLYLINEPOINTS[DRAWPOLYLINEPOINTS.length - 1];
		        DRAWMOVEPOLYLINE = new L.Polyline([prevPoint, e.latlng], shapeOptions);
		        _editLayer.addLayer(DRAWMOVEPOLYLINE);
		        if (ISMEASURE) {
		            let distance = MEASURERESULT + e.latlng.distanceTo(DRAWPOLYLINEPOINTS[DRAWPOLYLINEPOINTS.length - 1]);
		            MEASURETOOLTIP.updatePosition(e.latlng);
		            MEASURETOOLTIP.updateContent({
		                text: `<div class="leaflet-draw-tooltip-textdiv">单击确定点，双击结束！</div>`,
		                subtext: `总长：${(distance / 1000).toFixed(2)}公里`
		            });
		        }
		    }
		});
		_map.on('dblclick', function (e) {
		    _map.getContainer().style.cursor = '';
		    if (DRAWING) {
		        if (DRAWMOVEPOLYLINE != undefined && DRAWMOVEPOLYLINE != null) {
		            _editLayer.removeLayer(DRAWMOVEPOLYLINE);
		            DRAWMOVEPOLYLINE = null;
		        }
		        if (DRAWPOLYLINEPOINTS.length > 1 && ISMEASURE) {
		            MEASURERESULT += e.latlng.distanceTo(DRAWPOLYLINEPOINTS[DRAWPOLYLINEPOINTS.length - 2]);
		            let distanceLabel = L.marker(DRAWPOLYLINEPOINTS[DRAWPOLYLINEPOINTS.length - 1], {
		                icon: new L.divIcon({
		                    className: 'DistanceLabelStyle',
		                    iconAnchor: [-8, 15],
		                    html: "<span class='bubbleLabel' style='background-color:white !important;border:1px solid black !important;color:black !important;font-weight:normal !important;white-space:nowrap;position:absolute;border:1px solid rgb(190,206,235);border-radius:3px;display:inline-block;padding:2px 5px;position:relative;text-align:center;'>"+
							"<span class='bubbleLabel-bot bubbleLabel-bot-left' style='border-color:transparent black transparent transparent !important;border-width:8px;font-size:0;height:0;overflow:hidden;position:absolute;width:0;border-color:rgba(0,0,0,0) rgb(190,206,235) rgba(0,0,0,0) rgba(0,0,0,0);border-style:dashed solid dashed dashed;left:-15px;top:3px;'></span>"+
							"<span class='bubbleLabel-top bubbleLabel-top-left' style='border-color:transparent white transparent transparent !important;border-width:8px;font-size:0;height:0;overflow:hidden;position:absolute;width:0;border-color:rgba(0,0,0,0) rgb(255,165,0) rgba(0,0,0,0) rgba(0,0,0,0);border-style:dashed solid dashed dashed;left:-14px;top:3px;'></span>"+
							"<span>总长：" + (MEASURERESULT / 1000).toFixed(2) + "公里" + "</span></span>"
		                }),
		            }).addTo(_editLayer);
		            BarDRAWLAYERS.push(distanceLabel);
		        }
		        //移除提示框
		        if (MEASURETOOLTIP) {
		            MEASURETOOLTIP.dispose();
		        }
		        BarDRAWLAYERS.push(DRAWPOLYLINE);
		        if (func) {
		            func(DRAWPOLYLINEPOINTS);
		        }
		        DRAWPOLYLINEPOINTS = [];
		        DRAWING = false;
		        ISMEASURE = false;
		        _map.off('mousedown');
		        _map.off('mousemove');
		        _map.off('dblclick');
		    }
		});
		const shapeOptions = {
		        color: '#F54124',
		        weight: 3,
		        opacity: 0.8,
		        fill: false,
		        clickable: true
		    },
		    DRAWPOLYLINE = new L.Polyline([], shapeOptions);
		_editLayer.addLayer(DRAWPOLYLINE);
		if (ISMEASURE) {
		    MEASURETOOLTIP = new L.Tooltip(_editLayer);
		}
	}
	/**
	 * 测面
	 */
	this.startDrawPolygon = function(func){
		const that = this;
		MEASURERESULT = 0;
		_map.getContainer().style.cursor = 'pointer';
		_map.on('mousedown', function (e) {
		    DRAWING = true;
		    DRAWPOLYGONPOINTS.push(e.latlng);
		    DRAWPOLYGON.addLatLng(e.latlng);
		});
		_map.on('mousemove', function (e) {
		    if (DRAWING) {
		        if (DRAWMOVEPOLYGON != undefined && DRAWMOVEPOLYGON != null) {
		            _editLayer.removeLayer(DRAWMOVEPOLYGON);
		        }
		        let prevPoint = DRAWPOLYGONPOINTS[DRAWPOLYGONPOINTS.length - 1];
		        let firstPoint = DRAWPOLYGONPOINTS[0];
		        DRAWMOVEPOLYGON = new L.Polygon([firstPoint, prevPoint, e.latlng], shapeOptions);
		        _editLayer.addLayer(DRAWMOVEPOLYGON);
		        if (ISMEASURE && DRAWPOLYGONPOINTS.length > 1) {
		            let tempPoints = [];
		            for (let i = 0; i < DRAWPOLYGONPOINTS.length; i++) {
		                tempPoints.push(DRAWPOLYGONPOINTS[i]);
		            }
		            tempPoints.push(e.latlng);
		            let distance = that.CalArea(tempPoints);
		            MEASUREAREATOOLTIP.updatePosition(e.latlng);
		            MEASUREAREATOOLTIP.updateContent({
		                text: `<div class="leaflet-draw-tooltip-textdiv">单击确定点，双击结束！</div>`,
		                subtext: `总面积：${(distance / 1000000).toFixed(3)}平方公里`
		            });
		        }
		    }
		});

		_map.on('dblclick', function (e) {
		    _map.getContainer().style.cursor = '';
		    if (DRAWING) {
		        if (DRAWMOVEPOLYGON != undefined && DRAWMOVEPOLYGON != null) {
		            _editLayer.removeLayer(DRAWMOVEPOLYGON);
		            DRAWMOVEPOLYGON = null;
		        }
		        if (DRAWPOLYGONPOINTS.length > 2 && ISMEASURE) {
		            MEASURERESULT = that.CalArea(DRAWPOLYGONPOINTS);
		            let distanceLabel = L.marker(e.latlng, {
		                icon: new L.divIcon({
		                    className: 'DistanceLabelStyle',
		                    iconAnchor: [-8, 15],
		                    html: "<span class='bubbleLabel' style='background-color:white !important;border:1px solid black !important;color:black !important;font-weight:normal !important;white-space:nowrap;position:absolute;border:1px solid rgb(190,206,235);border-radius:3px;display:inline-block;padding:2px 5px;position:relative;text-align:center;'>"+
							"<span class='bubbleLabel-bot bubbleLabel-bot-left' style='border-color:transparent black transparent transparent !important;border-width:8px;font-size:0;height:0;overflow:hidden;position:absolute;width:0;border-color:rgba(0,0,0,0) rgb(190,206,235) rgba(0,0,0,0) rgba(0,0,0,0);border-style:dashed solid dashed dashed;left:-15px;top:3px;'></span>"+
							"<span class='bubbleLabel-top bubbleLabel-top-left' style='border-color:transparent white transparent transparent !important;border-width:8px;font-size:0;height:0;overflow:hidden;position:absolute;width:0;border-color:rgba(0,0,0,0) rgb(255,165,0) rgba(0,0,0,0) rgba(0,0,0,0);border-style:dashed solid dashed dashed;left:-14px;top:3px;'></span>"+
							"<span>总面积：" + (MEASURERESULT / 1000000).toFixed(3) + "平方公里" + "</span></span>"
		                }),
		            }).addTo(_editLayer);
		            BarDRAWLAYERS.push(distanceLabel);
		        }
		        //移除提示框
		        if (MEASUREAREATOOLTIP) {
		            MEASUREAREATOOLTIP.dispose();
		        }
		        BarDRAWLAYERS.push(DRAWPOLYGON);
		        if (func) {
		            func(DRAWPOLYGONPOINTS);
		        }
		        DRAWPOLYGONPOINTS = [];
		        DRAWING = false;
		        ISMEASURE = false;
		        _map.off('mousedown');
		        _map.off('mousemove');
		        _map.off('dblclick');
		    }
		});
		const shapeOptions = {
		        color: '#F54124',
		        weight: 3,
		        opacity: 0.8,
		        fill: true,
		        fillColor: null,
		        fillOpacity: 0.2,
		        clickable: true
		    },
		    DRAWPOLYGON = new L.Polygon([], shapeOptions);
		_editLayer.addLayer(DRAWPOLYGON);
		if (ISMEASURE) {
		    MEASUREAREATOOLTIP = new L.Tooltip(_editLayer);
		}
	}
	/**
	 * 面积计算
	 */
	this.CalArea = function(latlngss){
		let pointsCount = latlngss.length;
		let area = 0.0;
		let d2r = Math.PI / 180;
		let p1, p2;
		if (pointsCount > 2) {
		    for (let i = 0; i < pointsCount; i++) {
		        p1 = latlngss[i];
		        p2 = latlngss[(i + 1) % pointsCount];
		        area += ((p2.lng - p1.lng) * d2r) *
		            (2 + Math.sin(p1.lat * d2r) + Math.sin(p2.lat * d2r));
		    }
		    area = area * 6378137.0 * 6378137.0 / 2.0;
		}
		return Math.abs(area);
	}
	/**
	 * 距离计算
	 */
	this.CalDistances = function(points){
		let distance = 0;
		if (points != undefined) {
		    for (let i = 0; i < points.length - 1; i++) {
		        let point = points[i];
		        let point1 = points[i + 1];
		        distance += this.CalDistance(point, point1);
		    }
		}
		return distance;
	}
	/**
	 * 地图左边转为屏幕坐标
	 */
	this.ConverterCoordToGrauss = function(point){
		let x = point.x * 20037508.34 / 180;
		let y = Math.log(Math.tan((90 + point.y) * Math.PI / 360)) / (Math.PI / 180);
		y = y * 20037508.34 / 180;
		let newPoint = { 'x': x, 'y': y };
		return newPoint;
	}
}
export default LineMeasure;
